const express = require('express')
const router = express.Router()
const {getDb, saveDb} = require('../utils/db')

router.get('',async (req,res)=>{
  try {
    const db = await getDb("../mock/project.json");
    res.json(db)
  } catch (error) {
    res.status(500).json({
      error: error.message,
    });
  }
})

router.post('',async (req,res)=>{
  try {
    const project = req.body;
    if(!project.name){
      return res.status(401).json({
        error:'请添加项目名'
      })
    } 
    let projects =await getDb("../mock/project.json")
    let lastProject = projects[projects.length -1]
    if(lastProject === undefined){
      lastProject = new Object()
      lastProject.ownerId = 193361109
    }
    project.id = lastProject.id? lastProject.id +1 : 1;
    project.created = new Date().getTime()
    project.ownerId = lastProject.ownerId
    projects.push(project)

    await saveDb(projects,"../mock/project.json")
    // projects =await getDb("../mock/project.json")

    res.status(200).json(projects)
  } catch (error) {
    res.status(500).json({
      error:error.message
    })
  }
})

router.patch('/:id',async (req,res)=>{
  try {
    const projects =await getDb("../mock/project.json")
    const getproject = projects.find(project => project.id === +req.params.id)
    const getprojectInedx = projects.findIndex(project => project.id === +req.params.id)
    if(getprojectInedx === -1){
      return res.status(402).json("没有数据，先添加！")
    }
    const project = req.body;
    projects[getprojectInedx] = {...getproject,...project}

    await saveDb(projects,"../mock/project.json")

    res.status(200).json(projects)
  } catch (error) {
    
  }
})

router.delete('/:id',async (req,res)=>{
  let projects =await getDb("../mock/project.json")
  const getprojectInedx = projects.findIndex(project => project.id === +req.params.id)
  console.log(getprojectInedx);
  if(getprojectInedx ===-1){
    return res.status(402).json('找不到要删除的内容')
  }
  projects.splice(getprojectInedx,1)
  await saveDb(projects,"../mock/project.json")
  projects =await getDb("../mock/project.json")

  res.status(200).json(projects)
})
module.exports = router